package com.dabai.qrtools.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import java.util.List;

public class WifiManage {

    private static String TAG = "dabaizzz";


    /**
     * 忘记全部wifi密码
     *
     * @param wifiManager
     */
    public static void removeAllWifi(Context context, WifiManager wifiManager) {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "缺少必要的定位权限，删除失败！", Toast.LENGTH_SHORT).show();
            return;
        }
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();

        for (WifiConfiguration wifiConfig : wifiConfigs) {
            String ssid = wifiConfig.SSID;

            Log.d(TAG, "删除WiFi success, SSID = " + wifiConfig.SSID + " netId = " + String.valueOf(wifiConfig.networkId));
            wifiManager.removeNetwork(wifiConfig.networkId);
            wifiManager.saveConfiguration();

        }
        Toast.makeText(context, "删除" + wifiConfigs.size() + "个WiFi信息！", Toast.LENGTH_LONG).show();
    }


    /**
     * 删除无线网络的名称
     * 忘记某一个wifi密码
     *
     * @param context     上下文
     * @param wifiManager 无线管理器
     * @param targetSsid  目标名称
     */
    public static void removeWifiBySsid(Context context,WifiManager wifiManager, String targetSsid) {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "缺少必要的定位权限，删除失败！", Toast.LENGTH_SHORT).show();
            return;
        }

        Log.d(TAG, "try to removeWifiBySsid, targetSsid=" + targetSsid);
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();

        for (WifiConfiguration wifiConfig : wifiConfigs) {
            String ssid = wifiConfig.SSID;
            Log.d(TAG, "removeWifiBySsid ssid=" + ssid);
            if (ssid.equals("\"" +targetSsid+"\"")) {
                Log.d(TAG, "removeWifiBySsid success, SSID = " + wifiConfig.SSID + " netId = " + String.valueOf(wifiConfig.networkId));
                wifiManager.removeNetwork(wifiConfig.networkId);
                wifiManager.saveConfiguration();
            }
        }
    }


}